package com.pay.game.central.web.service;

import com.fasterxml.uuid.Generators;
import com.github.pagehelper.Page;
import com.pay.game.central.system.mapper.UserMapper;
import com.pay.game.central.web.bean.*;
import com.pay.game.central.web.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class StoreService {

    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private SettlementMapper settlementMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RentMapper rentMapper;
    @Autowired
    private DirectoryService directoryService;
    @Autowired
    private PtScoreMapper ptScoreMapper;
    @Autowired
    private GoodsMapper goodsMapper;

//    public void addStore(String id,String name,String thumb_url){
//        if (storeMapper.queryById(id) == null)
//            storeMapper.addStore(id, name, thumb_url,"", System.currentTimeMillis());
//    }

    public void updateOrAddStore(String id, String name, String thumb_url, String userId, String orderIndex){
        if (storeMapper.queryById(id) == null)
            storeMapper.addStore(id, name, thumb_url, userId, System.currentTimeMillis(), orderIndex);
        else {
            storeMapper.updateStore(id, name, thumb_url, userId, System.currentTimeMillis(), orderIndex);
        }

    }

    public void addStores(List<Store> stores){
        storeMapper.addStores(stores);
    }

    public Page<Store> queryAll(){
        return storeMapper.queryAll();
    }
    public Page<Store> searchById(String id){
        return storeMapper.searchById(id);
    }

    public Page<Map<String,Object>> list(String id, String name, String username){
        return storeMapper.list(id, name, username);
    }

    public void deleteById( String id){
        storeMapper.deleteById(id);
    }

    public List<Store> getNotSpider(){
        return storeMapper.getNotSpider();
    }

    public void startLoop(String id){
        Map<String,Object> map = storeMapper.queryContainUserInfoById(id);
        Store store = new Store();
        store.setId(map.get("id").toString());
        store.setUser_id(map.get("user_id").toString());
        store.setLoop((Boolean) map.get("loop"));
        store.setName((String) map.get("name"));
        if (!store.isLoop()){
            start(Collections.singletonList(store), (String) map.get("user_name"));
        }
    }

    public void stopLoop(String id, String userId){
        Store store = storeMapper.queryById(id);
        if (store.isLoop()){
            stop(Collections.singletonList(store), userId);
        }
    }

    public void setStoreUDateTime(String id,long update_time){
        storeMapper.setStoreUDateTime(id,update_time);
    }

    public Page<Store> getUserStore(String userId){
        return storeMapper.getUserStore(userId);
    }

    public Page<Map> getUserStoreDetail(String userId){
        return storeMapper.getUserStoreDetail(userId);
    }

    public void setStoreUserId(String storeId,String userId){
        storeMapper.setStoreUserId(storeId,userId);
    }

    public void setStoresUserId(List<String> storeIds,String userId){
        storeMapper.setStoresUserId(storeIds,userId);
    }

    /**
     * 删除一个用户的店铺
     * @param userId
     */
    public void removeUserId(String userId){
        storeMapper.removeUserId(userId);
    }

    public List<Store> queryNoUserId(String storeId){
        return storeMapper.queryNoUserId(storeId);
    }

    public void addScore(String storeId, int score){
        storeMapper.addScore(storeId, score);
    }

    public void setScore(String storeId, String userId, int score){
        storeMapper.setScore(storeId, score);
        PtScore ptScore = new PtScore();
        ptScore.setId(Generators.timeBasedGenerator().generate().toString());
        ptScore.setOpt_time((int) (System.currentTimeMillis()/1000));
        ptScore.setStore_id(storeId);
        ptScore.setValue(score);
        ptScore.setUser_id(userId);
        //保存记录
        ptScoreMapper.insertItem(ptScore);
    }

    public void addUsedScore(String goodsId, int value){
        storeMapper.addUsedScore(goodsId, value);
    }

    public void decreaseOrderLimit(String goodsId){
        storeMapper.decreaseOrderLimit(goodsId);
    }

    public void increaseOrderLimit(String goodsId){
        storeMapper.increaseOrderLimit(goodsId);
    }

    /**
     * 用户下的所有店开始跑分
     * @param userId
     */
    public void startByUserId(String userId){
        List<Store> stores = storeMapper.getUserStore(userId);

        if (null!=stores && !stores.isEmpty()){
             //找出没开始跑分的店铺
             List<Store> notStartStores = stores.stream().filter(item -> !item.isLoop()).collect(Collectors.toList());
             if (!notStartStores.isEmpty()) {
                 start(notStartStores, userMapper.getNameById(userId).getName());
             }
        }
    }

    public void stopByUserId(String userId){
        List<Store> stores = storeMapper.getUserStore(userId);
        if (null!=stores && !stores.isEmpty()){
            List<Store> notStopStores = stores.stream().filter(Store::isLoop).collect(Collectors.toList());
            if (!notStopStores.isEmpty()){
                stop(notStopStores, userId);
            }
        }
    }

    /**
     * 开启一组商店的跑分
     * @param stores
     */
    private void start(List<Store> stores,String username){
        long timestamp = System.currentTimeMillis();
        int time = (int) (timestamp / 1000);
        Date date = new Date(timestamp);
        // 生成结算单
        List<Settlement> settlements = stores.stream()
                .map(store -> {
                    Settlement settlement = new Settlement();
                    settlement.setUser_id(store.getUser_id());
                    settlement.setUser_name(username);
                    settlement.setStore_id(store.getId());
                    settlement.setStore_name(store.getName());
                    settlement.setStart_date(date);
                    settlement.setStart_time(time);
                    return settlement;
                })
                .collect(Collectors.toList());
        settlementMapper.addSettlements(settlements);
        // 设置店铺当前结算单
        settlements.forEach(item -> {
            storeMapper.setStartScoreParams(item.getStore_id(), time, item.getId());
        });
    }

    private void stop(List<Store> stores,
                      String userId){
        Map<String,Object> userInfo = userMapper.getRateAndFatherRate(userId);
        float rate = (float) userInfo.get("rate");
        Object fatherRate = userInfo.get("father_rate");
        boolean hasParent = fatherRate != null;
        float parentRate = hasParent ? (float) fatherRate : 0f;
        List<Settlement> settlements = settlementMapper.queryByIds(stores.stream().map(Store::getSettlement_id).collect(Collectors.toList()));
        Map<Long,Store> map = new HashMap<>();
        stores.forEach(item -> {
            map.put(item.getSettlement_id(),item);
            goodsMapper.deleteGroupOrderId(item.getId());
        });
        long timestamp = System.currentTimeMillis();
        int time = (int) (timestamp / 1000);
        Date date = new Date(timestamp);
        settlements.forEach(settlement -> {
            settlement.setStop_time(time);
            settlement.setRate(rate);
            settlement.setStop_date(date);
            Store store = map.get(settlement.getId());
            settlement.setValue((int) (store.getUsed_score() * rate));
            settlement.setRun_score(store.getUsed_score());
            settlement.setScore(store.getScore());
        });
        if (hasParent){
            // 计算租金
            List<Rent> rents = new ArrayList<>();
            String userName = userInfo.get("user_name").toString();
            String pUserId = userInfo.get("p_user_id").toString();
            String pUserName = userInfo.get("p_user_name").toString();
            settlements.forEach(item -> {
                Rent rent = new Rent();
                rent.setDate(date);
                rent.setTime(time);
                rent.setSettlement_id(item.getId());
                rent.setStore_id(item.getStore_id());
                rent.setStore_name(item.getStore_name());
                rent.setRate(rate);
                rent.setRun_score(item.getRun_score());
                rent.setUser_id(userId);
                rent.setFather_rate(parentRate);
                rent.setUser_name(userName);
                rent.setP_user_id(pUserId);
                rent.setP_user_name(pUserName);
                if (parentRate == rate){
                    rent.setValue(0);
                }else {
                    rent.setValue((int) (item.getValue() * (parentRate - rate)));
                }
                rents.add(rent);
            });
            //保存租金
            rentMapper.addRents(rents);
        }

        settlements.forEach(set -> {
            //保存结算数据
            settlementMapper.updateSettlementToStop(set);
//            //减去已经跑的分
//            storeMapper.subtractScore(set.getStore_id(), set.getRun_score());
            // 清空跑分信息
            storeMapper.clearScore(set.getStore_id());
        });
        // 停止店铺跑分
        storeMapper.setStopScoreParams(stores.stream().map(Store::getId).collect(Collectors.toList()));
    }
}

